/*
* FileUp.java
* Created on  2014-5-7 下午7:34
* 版本       修改时间          作者      修改内容
* V1.0.1    2014-5-7       panzhuowen    初始版本
*
*/
package com.genghis.ptas.util;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 类的描述信息
 *
 * @author panzhuowen
 * @version 1.0.1
 */
public class FileUp {

    public FileUp() {
    }

    public void upLoadFile(InputStream inputStream, String filePath, String fileName) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(filePath + fileName);
            byte[] bytes = new byte[1024];
            int length = 0;
            while ((length = (inputStream.read(bytes))) != -1) {
                fileOutputStream.write(bytes, 0, length);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }

    public InputStream getInputStream(MultipartHttpServletRequest request, String fileIn) throws IOException {
        MultipartFile multipartFile = request.getFile(fileIn);
        return multipartFile.getInputStream();
    }

    public String upData(HttpServletRequest request, String path, String upFile, String fileName) throws IOException, ServletException {
        String upDataPath = request.getSession().getServletContext().getRealPath("");
        upDataPath = upDataPath + "/" + "data" + "/" + path + "/";
        File file = new File(upDataPath);
        file.mkdirs();
        InputStream inputStream = getInputStream((MultipartHttpServletRequest) request, upFile);
        upLoadFile(inputStream, upDataPath, fileName);
        return upDataPath;
    }


}
